package com.wangwei.modules.servlet

import com.wangwei.modules.servlet.spring.Autowired
import com.wangwei.modules.servlet.spring.Component
import com.wangwei.modules.utils.ann.AnnUtil
import com.wangwei.modules.utils.scan.ClasspathPackageScanner


object ComponentFactory {

	//根据类型取
	var classComponentMap = hashMapOf<Class<*>, Any>();


	/**
	 * 获取容器里面的类
	 * @param clazz
	 * @return
	 */
	fun getBeanByClass(clazz: Class<*>) = classComponentMap.get(clazz);


	fun addBean(clazz: Class<*>, obj: Any) = classComponentMap.put(clazz, obj);


	/**
	 * 初始化所有容器
	 * @param path
	 * @throws IOException
	 * @throws ClassNotFoundException
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	fun initAllComponent(path: String) {

		//获取所有的类
		var clazzList = ClasspathPackageScanner(path).getFullyQualifiedClassNameList();
		for (string in clazzList) {
			var clazz = Class.forName(string);
			if (AnnUtil.checkClassHasAnn(clazz, Component::class.java)) {
				try {
					addBean(clazz, clazz.newInstance());
				} catch (e: Exception) {
					println("$clazz 无法实例化");
				}
			}
		}
	}


	/**
	 * 依赖类型进行注入
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	fun autowiredAll() {
		for ((clazz, clazzInstance) in classComponentMap) {

			//获取所有属性，判断是否有注入需求
			var fields = clazz.getDeclaredFields();
			for (field in fields) {
				if (field.getAnnotation(Autowired::class.java) != null) {
					field.setAccessible(true);
					field.set(clazzInstance, classComponentMap[field.getType()]);
				}
			}
		}
	}
}